package demo;

/**
 *  岛屿数量
 */
class Solution20 {
	public int numIslands(char[][] grid) {
		if (grid == null || grid.length == 0) {
			return 0;
		}
		int row = grid.length;
		int columns = grid[0].length;
		int count = 0;
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < columns; j++) {
				if (grid[i][j] == '1') {
					dfs(grid, i, j, row, columns);
					count++;
				}
			}
		}

		return count;
	}

	private void dfs(char[][] grid, int i, int j, int row, int columns) {
		if (i < 0 || j < 0 || i >= row || j >= columns || grid[i][j] == '0') {
			return;
		}
		grid[i][j] = '0';
		dfs(grid, i + 1, j, row, columns);
		dfs(grid, i, j + 1, row, columns);
		dfs(grid, i - 1, j, row, columns);
		dfs(grid, i, j - 1, row, columns);
	}
}

